<?php

namespace app\api\controller;

use app\api\controller\Auth;
use app\api\model\Token;
use app\api\model\User as userModel;
use app\common\controller\ApiController;
use app\Request;
use Icharle\Wxtool\Wxtool;
use think\App;
use think\facade\Db;
use think\facade\Log;
use app\api\controller\JSSDK;


class User extends ApiController
{
    protected $noNeedLogin = ['wx_login','getopenid','getphone',"get_location","wx_newlogin"];
    /**
     * 登录
     * @return string
     * @throws \Exception
     */
    public function wx_login(userModel $user)
    {
        $param = $this->request->param();
       
        $wx = new Wxtool();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        // if (empty($param['code']) || empty($param['encryptedData']) || empty($param['iv'])) {
        //     $this->error("参数有误");
        // }
        $code = $param['code'];
        // $encryptedData = urldecode($param['encryptedData']);
        // $iv = urldecode($param['iv']);
        $res = $wx->GetSessionKey($code);

        $nickName = nickname();
        $avatarUrl = "https://ls.yquewx.com/upload/login.jpg";

        $openId = $res['openid'];
      //  $unionId = empty($res['unionid']) ? '' : $res['unionid'];
        $isExit = $user->where('wx_openid', $openId)->find();
        //'unionId' => $unionId,   "nickname" => $nickName, 
        $saveData = ['update_time' => time(), 'avatar' => $avatarUrl];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $gender = $isExit["gender"];
            $nickName = $isExit["nickname"];
        } else {
            $user = new userModel();
            $saveData['wx_openid'] = $openId;
            $saveData['nickname'] = $nickName;
            $ret = $user->save($saveData);
            $uid = $user->id;
            $gender = $user->gender;
        }  
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'avatar' => $avatarUrl,"uid"=>$uid,"gender"=>$gender];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败,请稍后重试001');
        }
    }


    public function getopenid(){
        $param = $this->request->param();
        $wx = new Wxtool();
        if (empty($param['code'])) {
            $this->error("参数有误");
        }
        $code = $param['code'];
        $res = $wx->GetSessionKey($code);
        $this->success('登录成功', $res);
    }

    public function getphone(userModel $user){
        $param = $this->request->param();
        $wx = new Wxtool();
        // if (empty($param['session_key']) || empty($param['encryptedData']) || empty($param['iv']) || empty($param['openid'])) {
        //     $this->error("参数有误");
        // }
        if (empty($param['code']) || empty($param['encryptedData']) || empty($param['iv'])) {
            $this->error("参数有误");
        }
        $code = $param['code'];
        $res = $wx->GetSessionKey($code);
       
        $encryptedData = urldecode($param['encryptedData']);
        $iv = urldecode($param['iv']);
        $userinfo = $wx->GetUserInfo($encryptedData, $iv,$res['session_key']);
        $userinfo = json_decode($userinfo, true);
        $openId = $res['openid'];
        $phone = empty($userinfo['phoneNumber']) ? '' : $userinfo['phoneNumber'];
        //dump($phone);die;
        //'unionId' => $unionId,
        //$unionId = empty($param['unionid']) ? '' : $param['unionid'];
        $nickName = nickname();
        $avatarUrl = "https://ls.yquewx.com/upload/login.jpg";
        $isExit = $user->where('wx_openid', $openId)->find();
        $saveData = [ 'update_time' => time(), 'gender' => 0, 'avatar' => $avatarUrl,'phone' => $phone];
        if (!empty($isExit)) {
            $uid = $isExit['id'];
            $ret = $user->where('id', $uid)->update($saveData);
            $nickName = $isExit["nickname"];
            
        }else {
            $user = new userModel();
            $saveData['wx_openid'] = $openId;
            $saveData['nickname'] = $nickName;
            $ret = $user->save($saveData);
            $uid = $user->id;
        }
        // file_put_contents('wx.log', "ret:" . $ret . PHP_EOL, FILE_APPEND);
        if ($ret) {
            $token = Auth::makeToken();
            $userToken = new Token();
            $userToken->setToken($token, $uid, $this->method);
            $user_info = ['nickname' => $nickName, 'phone' => $phone,'avatar' => $avatarUrl,"uid"=>$uid];
            $this->success('登录成功', ['token' => $token, 'method' => $this->method, 'user_info' => $user_info]);
        } else {
            $this->error('登陆失败，请稍后重试1');
        }
        
    }
 

     
    //授权链接
    public function authorization_link(){
        $appid = 'your_app_id';
        $redirect_uri = urlencode('http://shiwan.charityzimi.cn/api/user/callback.php'); // 回调地址
        $auth_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        $this->success('获取成功', $auth_url);
    }

    public function callback(){
        $appid = 'your_app_id';
        $appsecret = 'your_app_secret';
        $code = $_GET['code']; // 获取授权码
        // 向微信API发送请求，用授权码换取access_token
        $token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$appsecret}&code={$code}&grant_type=authorization_code";
        $response = file_get_contents($token_url);
        $token = json_decode($response, true);
    
        if ($token['access_token']) {
            // 获取用户信息
            $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token={$token['access_token']}&openid={$token['openid']}&lang=zh_CN";
            $user_info_response = file_get_contents($user_info_url);
            $user_info = json_decode($user_info_response, true);
    
            // 用户信息处理逻辑（比如保存用户信息到数据库）
            // ...
    
            // 登录流程结束，可以跳转到首页或其他页面
          
        } else {
            // 错误处理
            // ...
        }
    }

  
 
     


}
